# Contributor: G.J.R. Timmer <gjr.timmer@gmail.com>
# Maintainer: rubicon <rubicon@mailo.com>
pkgname=pgtcl
pkgver=3.0.1
pkgrel=0
pkgdesc="Tcl client side interface to PostgreSQL (libpgtcl)"
url="https://flightaware.github.io/Pgtcl/"
arch="all"
license="BSD-3-Clause"
depends="tcl"
makedepends="autoconf libpq-dev tcl-dev"
checkdepends="postgresql"
subpackages="$pkgname-doc $pkgname-dev"
source="$pkgname-$pkgver.tar.gz::https://github.com/flightaware/Pgtcl/archive/v$pkgver.tar.gz
	pgtcl-tests.patch
	"
builddir="$srcdir/Pgtcl-$pkgver"

ERROR_CLEANUP="$ERROR_CLEANUP srcdir"

cleanup_srcdir() {
	if [ -f "$_data_dir"/postmaster.pid ]; then
		local pg_pid="$(head -1 "$_data_dir"/postmaster.pid)"
		msg "Killing PostgreSQL test server with PID: $pg_pid"
		kill "$pg_pid"
	fi
	default_cleanup_srcdir
}

prepare() {
	default_prepare
	sed -i "s/@USER@/${USER:-$(id -un)}/" tests/conninfo.tcl
	autoupdate
	autoreconf -fiv
}

build() {
	local x64_flags
	case "$CARCH" in
	aarch64 | x86_64) x64_flags="--enable-64bit";;
	esac

	./configure \
		--build=$CBUILD \
		--host=$CHOST \
		--prefix=/usr \
		--mandir=/usr/share/man \
		--disable-rpath \
		--enable-threads \
		$x64_flags
	make
}

check() {
	export PATH="/usr/libexec/postgresql:$PATH"
	_data_dir="$srcdir"/pgtcltest
	local socket_dir="$srcdir"

	rm -vrf "$_data_dir"
	mkdir -vp "$_data_dir"
	pg_ctl initdb -D "$_data_dir"
	pg_ctl start -D "$_data_dir" -o -k"$socket_dir"
	createdb -h "$socket_dir" pgtcl

	make test TESTFLAGS="-verbose pbtels -notfile 'sqlite3.test'"
	cd tests
	psql -h "$socket_dir" -d pgtcl -c '\i create.sql'
	local test; for test in import*.tcl; do
		msg "Testing $test"
		time tclsh $test
	done

	pg_ctl stop -D "$_data_dir" -m immediate
}

package() {
	make DESTDIR="$pkgdir" install

	# Remove empty directories.
	rmdir -v "$pkgdir"/usr/bin
}

sha512sums="
a50eca8d48b88439747e43e32c7e79e325ac73d2864467e0713b3c8e2ea811942780baef3283796c4eb9ee618b55fa10af75737e4972f77293c6eca831213e66  pgtcl-3.0.1.tar.gz
8c9f5bf024919dd59f29ecc99d1be305169c1a6a8dcad1ff0bcaefda4e1d206731b867340167adf44f7e607745152a7745a4d1dc4a67f835de469990ed9e1cd8  pgtcl-tests.patch
"
